﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlowBasis.Data;
using FlowBasisSampleSite.Domain.Entities;
using System.Net;
using FlowBasis.Web.Mvc;
using System.Collections;
using FlowBasis.Json;

namespace FlowBasisSampleSite.Areas.Admin.Controllers
{

    [UserAuthorize(RequiredPermissions = new[] { FlowBasis.Security.BasicPermissions.SiteAdmin })]
    public class RolesController : Controller
    {
        private IDataService dataService;
        private Func<IUnitOfWork> unitOfWorkFactory;

        public RolesController(IDataService dataService, Func<IUnitOfWork> unitOfWorkFactory)
        {
            this.dataService = dataService;
            this.unitOfWorkFactory = unitOfWorkFactory;
        }

        public ActionResult Index()
        {
            List<Role> roles = this.dataService.GetAll<Role>()
                .OrderBy(r => r.Name)
                .ToList();

            ViewBag.Roles = roles;

            return View();
        }

        public ActionResult Info(int id)
        {
            Role role = this.dataService.GetAll<Role>().FirstOrDefault(r => r.RoleId == id);
            if (role == null)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);
            }

            ViewBag.Role = role;

            return View();
        }


        [PostRpc]
        public ActionResult GetRoleList(
            RoleQuery query,
            int? offset,
            int? maxResults)
        {
            if (query == null)
                query = new RoleQuery();
            
            IQueryable<Role> roleQuery = this.dataService.GetAll<Role>();

            if (!String.IsNullOrWhiteSpace(query.MatchText))
            {
                string matchText = query.MatchText.Trim();

                roleQuery = roleQuery.Where(ua => ua.Name.Contains(matchText));
            }

            roleQuery = roleQuery.OrderBy(ua => ua.Name);

            var resultSet = roleQuery.ToJObjectResultSet(
                offset,
                maxResults,
                (role) =>
                {                    
                    dynamic roleData = new JObject();
                    roleData.id = role.RoleId;
                    roleData.name = role.Name;

                    return roleData;
                });

            return new PostRpcResult(resultSet);
        }


        public class RoleQuery
        {
            public string MatchText { get; set; }            
        }
    }
}
